import React, { useState, useEffect } from 'react';
import { App, Button, Drawer, Radio, Table, Select, Tabs, Empty, Typography, Input } from 'antd';
import Image from 'next/image';
import { useTranslation } from 'react-i18next';
import './inDetail.css';
import { ReloadOutlined, DownOutlined, EditOutlined, SaveOutlined } from '@ant-design/icons';
import copy from 'copy-to-clipboard';
import { metricmodelInfoGet, indicatorModelLog, tableDetailsInfo, sqlExecute, update_gen_comment } from '@/client/api'
type TargetKey = React.MouseEvent | React.KeyboardEvent | string;
import { useRequest } from 'ahooks';
const inDetailContent: React.FC<{ open: Boolean, onClose: React.Dispatch<React.SetStateAction<boolean>>, modelType: string, currentItem: Object, measurementValue: Number }> = ({ open, onClose, modelType, currentItem, measurementValue }) => {
  const { t } = useTranslation();
  const { message } = App.useApp();
  const [logcreateTime, setlogcreateTime] = useState<any>([])
  const [basicData, setbasicData] = useState<any>({})
  const [detailData, setDetailData] = useState<any>({});
  const [dataSource, setdataSource] = useState<any>([]);
  const [attributeList, setAttributeList] = useState<any>([])
  const [logTableData, setlogTableData] = useState<any>([
  ]);
  const [logDisplayData, setlogDisplayData] = useState<any>([])
  const [previewDataSource, setPreviewDataSource] = useState<any>([
  ]);
  const [previewDataCount, setPreviewDataCount] = useState<any>(0)
  const [tabList, setTabList] = useState<any>([]);
  const [activeKey, setActiveKey] = useState('');
  const [logStatus, setlogStatus] = useState<any>('all')
  const onChange = (key: string) => {
    setActiveKey(key);
  };
  //获取时间
  const getNowAndPastDateWithTime = (days) => {
    const dates = [];
    const now = new Date();
    const pastDate = new Date();
    pastDate.setDate(now.getDate() - days);
    // 格式化函数
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };
    dates.push(formatDate(pastDate));
    dates.push(formatDate(now));
    return dates;
  };
  //表详情
  const { run: gettableDetailsInfo } = useRequest(
    async () => {
      return await tableDetailsInfo(currentItem?.key);
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { code, data, msg } = res.data || {};
        if (code == 0) {
          const result = data || {}
          setdataSource(result.columnDetail || [])
          return setDetailData(result)
        } else {
          message.error(`${msg}`);
        }
        return setDetailData({})
      },
      debounceWait: 10,
    },
  );
  //模型详情
  const { run: getbasicInformation } = useRequest(
    async () => {
      return await metricmodelInfoGet(currentItem && currentItem.modelInfo ? currentItem.modelInfo
        .id : '')
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { code, data, msg } = res.data || {};
        if (code == 0) {
          const result = data || {}
          setAttributeList([]);
          result?.metricModelTables.forEach((item: any) => {
            setAttributeList(prevList => [...prevList, ...item.metricModelTableColumns]);
          })
          setAttributeList(prevList =>
            prevList.map(item => {
              let label = '';
              let configuration = ''
              if (item.metricType === 'Metrics') {
                label = '度量';
                configuration = item.columnPrecision
              } else if (item.metricType === 'Dimension') {
                label = '维度';
                configuration = item.codeTableName
              }
              return {
                ...item,
                metricTypeLabel: label,
                configuration: configuration
              };
            })
          );
          return setbasicData(result);
        } else {
          message.error(`${msg}`);
        }
        return setbasicData({})
      },
      debounceWait: 10,
    },
  );
  //日志详情
  const { run: getindicatorModelLog } = useRequest(
    async () => {
      let params = {
        metricModelId: currentItem && currentItem.modelInfo ? currentItem.modelInfo.id : '',
        createTime: logcreateTime
      }
      return await indicatorModelLog(params)
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { code, data, msg } = res.data || {};
        if (code == 0) {
          const result = data || []
          const transformedData = result.map(item => {
            let log_type = '加速';
            let log_status = item.STATE === 'SUCCESS' ? '成功' : '失败';
            let log_record = `[指标加速]${item.TASK_NAME}${log_status}`;
            return {
              ...item,
              log_type,
              log_status,
              log_record
            };
          });
          setlogTableData(transformedData);
          setlogDisplayData(transformedData);
        } else {
          message.error(`${msg}`);
        }
        return setDetailData([])
      },
      debounceWait: 10,
    },
  );

  // 动态生成表头
  const previewColumns = React.useMemo(() => {
    const columns = [];
    const dataSource = previewDataSource;
    if (dataSource.length > 0) {
      const keys = Object.keys(dataSource[0]);
      keys.forEach(key => {
        // 确定排序函数
        let sorter = null;
        const firstValue = dataSource[0][key];
        if (typeof firstValue === 'number') {
          sorter = (a, b) => a[key] - b[key];
        } else if (typeof firstValue === 'string') {
          sorter = (a, b) => a[key].localeCompare(b[key]);
        }

        columns.push({
          title: key,
          dataIndex: key,
          key: key,
          width: '15%',
          sorter: sorter,
        });
      });
    }

    return columns;
  }, [previewDataSource]);

  // 改进 SQL 执行请求
  const { run: getsqlExecutetotal } = useRequest(
    async () => {
      let sql = currentItem && currentItem.modelInfo ? currentItem.modelInfo.metricSql : ''
      let params = {
        current: 1,
        size: 10,
        datasourceId: currentItem && currentItem.modelInfo ? currentItem.modelInfo.datasourceId : '',
        schemaName: currentItem && currentItem.modelInfo ? currentItem.modelInfo.databaseName : '',
        sql: `select count(*) as count1 from (${sql}) as a`
      };

      return await sqlExecute(params);
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { code, data, msg } = res.data || {};
        if (code === 0) {
          setPreviewDataCount(data[0].count1 || 0);
          const total = data[0].count1 || 0;
          const pageSize = 10;
          const currentPage = 1;
          const startinPoints = (currentPage - 1) * pageSize;
          // const destination = startinPoints + pageSize;
          getsqlExecute(startinPoints, pageSize);
        } else {
          setPreviewDataCount(0);
          message.error(`${msg}`);
        }
      },
      onError: (err) => {
        message.error(`请求错误: ${err.message}`);
      },
      debounceWait: 10,
    }
  );
  // 获取预览相关行数
  const { run: getsqlExecute } = useRequest(
    async (startinPoints, pageSize) => {
      let sql = currentItem && currentItem.modelInfo ? currentItem.modelInfo.metricSql : ''
      let params = {
        current: startinPoints || 1,
        size: pageSize || 10,
        datasourceId: currentItem && currentItem.modelInfo ? currentItem.modelInfo.datasourceId : '',
        schemaName: currentItem && currentItem.modelInfo ? currentItem.modelInfo.databaseName : '',
        sql: `${sql} limit ${pageSize} OFFSET ${startinPoints}  `
      };

      return await sqlExecute(params);
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { code, data, msg } = res.data || {};
        if (code === 0) {
          setPreviewDataSource(data || []);
        } else {
          setPreviewDataSource([]);
          message.error(`${msg}`);
        }
      },
      onError: (err) => {
        message.error(`${err.message}`);
      },
      debounceWait: 10,
    }
  );
  useEffect(() => {
    const isTabExists = tabList.some(tab => tab.key === modelType);
    if (modelType && !isTabExists) {
      const getLabel = () => {
        if (modelType === 'model') return '模型';
        if (modelType === 'log') return '日志';
        return '预览';
      };
      const newTab = { label: getLabel(), key: modelType };
      setTabList(prevTabList => [...prevTabList, newTab]);

    }
    setActiveKey(modelType);
    if (modelType == 'model') {
      getbasicInformation()
    } else if (modelType == 'log') {
      setlogcreateTime(getNowAndPastDateWithTime(7));
      getindicatorModelLog()
    } else if (modelType == 'table') {
      gettableDetailsInfo()
    } else {
      getsqlExecutetotal()
    }
  }, [modelType, currentItem?.key, measurementValue]);

  const remove = (targetKey: TargetKey) => {
    const newPanes = tabList.filter((pane) => pane.key !== targetKey);
    if (targetKey === activeKey) {
      if (newPanes.length > 0) {
        setActiveKey(newPanes[0].key);
      } else {
        setActiveKey('');
      }
    }
    if (!newPanes.length) {
      onClose(false)
    }
    setTabList(newPanes);
  };

  const onEdit = (targetKey: TargetKey, action: 'add' | 'remove') => {
    if (action === 'add') {
    } else {
      remove(targetKey);
    }
  };

  const columns = [
    {
      title: '列名',
      dataIndex: 'name',
      key: 'name',
      width: '12vw',
    },
    {
      title: '注释',
      dataIndex: 'comment',
      key: 'comment',
      width: '12vw',
    },
    {
      title: '类型',
      dataIndex: 'metricTypeLabel',
      key: 'metricTypeLabel',
      width: '12vw',
    },
    {
      title: '配置',
      dataIndex: 'configuration',
      key: 'configuration',
      width: '12vw',
    },
  ];

  const [editingGenCommentKey, setEditingGenCommentKey] = useState<string | null>(null);
  const [editingGenCommentValue, setEditingGenCommentValue] = useState<string>('');
  const { run: update_gen_commentRun } = useRequest(
    async (row) => {
      return await update_gen_comment({
        id: currentItem?.key + ':' + row.columnName,
        gen_comment: row.gen_comment,
      });
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { success, msg } = res.data || {};
        if (success) {
          gettableDetailsInfo()
          message.success(`${msg ?? '修改成功!'}`);
        } else {
          message.error(`${msg ?? '修改失败!'}`);
        }
      },
      debounceWait: 10,
    },
  );
  const dataTableColumn = [
    {
      title: '列名',
      dataIndex: 'columnName',
      key: 'columnName',
      width: '7vw',
      render: (value: string) => {
        return value || '-';
      },
    },
    {
      title: '类型',
      dataIndex: 'columnType',
      key: 'columnType',
      width: '7vw',
      render: (value: string) => {
        return value || '-';
      },
    },
    {
      title: '长度',
      dataIndex: 'columnLength',
      key: 'columnLength',
      width: '7vw',
      render: (value: string) => {
        return value || '-';
      },
    },
    {
      title: '精度',
      dataIndex: 'numericScale',
      key: 'numericScale',
      width: '7vw',
      render: (value: string) => {
        return value || '-';
      },
    },
    {
      title: '注释',
      dataIndex: 'columnComment',
      key: 'columnComment',
      width: '7vw',
      render: (value: string) => {
        return value || '-';
      },
    },
    {
      title: '注释生成',
      dataIndex: 'genComment',
      key: 'genComment',
      width: '7vw',
      render: (value: string, record: any) => {
        // 判断是否为当前编辑行
        if (editingGenCommentKey === record.genComment) {
          return (
            <span style={{ display: 'flex', alignItems: 'center' }}>
              <Input
                style={{ width: '100px', marginRight: 4 }}
                value={editingGenCommentValue}
                onChange={e => setEditingGenCommentValue(e.target.value)}
                autoFocus
              />
              <SaveOutlined
                style={{ color: '#1677ff', cursor: 'pointer' }}
                onClick={() => {
                  update_gen_commentRun({
                    gen_comment: editingGenCommentValue,
                    columnName: record.columnName,
                  })
                }}
              />
            </span>
          );
        }
        return (
          <span style={{ display: 'flex', alignItems: 'center' }}>
            <span className='max-w-[100px]'>{value || '-'}</span>
            <EditOutlined
              style={{ color: '#1677ff', marginLeft: 4, cursor: 'pointer' }}
              onClick={() => {
                setEditingGenCommentKey(record.genComment);
                setEditingGenCommentValue(value || '');
              }}
            />
          </span>
        );
      },
    },
    {
      title: '是否枚举',
      dataIndex: 'genIsEnum',
      key: 'genIsEnum',
      width: '7vw',
      render: (genIsEnum: boolean | 'true' | 'false') => {
        const boolValue = genIsEnum === 'true' || genIsEnum === true;
        return boolValue ? '是' : '否';
      },
    },
    {
      title: '枚举类型候选值',
      dataIndex: 'genEnumValues',
      key: 'genEnumValues',
      width: '7vw',
      render: (value: string) => {
        return value || '-';
      },
    },
    {
      title: '数据样例',
      dataIndex: 'genDataSamples',
      key: 'genDataSamples',
      width: '7vw',
      render: (value: string) => {
        return value || '-';
      },
    },
    {
      title: '数据取值范围',
      dataIndex: 'genDataRange',
      key: 'genDataRange',
      width: '7vw',
      render: (value: string) => {
        return value || '-';
      },
    },
  ];
  const logColumns = [
    {
      title: t('log_type'),
      dataIndex: 'log_type',
      key: 'log_type',
      width: '30%',
    },
    {
      title: t('log_status'),
      dataIndex: 'log_status',
      key: 'log_status',
      width: '30%',
    },
    {
      title: t('log_time'),
      dataIndex: 'CREATE_TIME',
      key: 'log_time',
      width: '30%',
    },
    {
      title: t('log_record'),
      dataIndex: 'log_record',
      key: 'log_record',
      width: '260px',
    },
  ];
  const handleChange = (value: string) => {
    setlogcreateTime(getNowAndPastDateWithTime(value));
    getindicatorModelLog()
  };
  const copyEvent = (value: string) => {
    const result = copy(value);
    if (result) {
      message.success('复制成功');
    } else {
      message.error('复制失败');
    }
  };
  const style = {
    padding: activeKey === 'model' ? '20px 70px 20px 70px' : activeKey === 'preview' ? '5px 0 0 0' : activeKey === 'table' ? '0' : '10px',
  };
  // 预览页码点击事
  const handlePageChange = (pageNumber, pageSize) => {
    const startinPoints = (pageNumber - 1) * pageSize;
    // const destination = startinPoints + pageSize;
    getsqlExecute(startinPoints, pageSize);
  };

  // 预览修改每页条数
  const handlePageSizeChange = (current, size) => {
    const startinPoints = (current - 1) * size;
    // const destination = startinPoints + size;
    getsqlExecute(startinPoints, size);
  };
  //日志
  const handleRadioChange = (e) => {
    let filteredData = []
    let targetType = e.target.value
    setlogStatus(targetType)
    if (targetType == 'all') {
      filteredData = [...logTableData]
    } else {
      filteredData = logTableData.filter((item) => item.STATE === targetType)
    }
    setlogDisplayData(filteredData)

  }
  return (
    <>
      {activeKey == 'table' ? (<div className='inDetail-content inDetail-content-table' style={{ height: '100%' }}>
        <div style={style}><div>
          <ul className='inDetail-content-ul ' >
            <h3 className='title' style={{ display: 'flex', justifyContent: 'space-between' }}>属性</h3>
            <div className='flex items-center gap-2'>
              <li className='w-72'>
                <span>名称：</span>
                <span className='overflow-hidden whitespace-nowrap text-ellipsis' style={{ maxWidth: '180px' }}>{detailData?.tableName || '-'}</span>
                {detailData?.tableName && <span onClick={() => copyEvent(detailData?.tableName)} className='ml-1 image-content'><Image alt='DB-GPT' height={15} width={15} src='/ai/workbenches/tabler-icon-copy.png' /></span>}
              </li>
              <li>
                <span>注释：</span>
                <span className='overflow-hidden whitespace-nowrap text-ellipsis' style={{ maxWidth: '350px' }}>{detailData?.tableComment || '-'}</span>
                {detailData.tableComment && <span onClick={() => copyEvent(detailData?.tableComment)} className='ml-1 image-content'><Image alt='DB-GPT' height={15} width={15} src='/ai/workbenches/tabler-icon-copy.png' /></span>}
              </li>
            </div>
            <div className='flex items-center gap-2'>
              <li className='w-72'>
                <span>主键：</span>
                <span className='overflow-hidden whitespace-nowrap text-ellipsis' style={{ maxWidth: '180px' }}>{detailData?.primaryKey || '-'}</span>
                {detailData?.primaryKey && <span onClick={() => copyEvent(detailData?.primaryKey)} className='ml-1 image-content'><Image alt='DB-GPT' height={15} width={15} src='/ai/workbenches/tabler-icon-copy.png' /></span>}
              </li>
              <li>
                <span>外键：</span>
                <span className='overflow-hidden whitespace-nowrap text-ellipsis' style={{ maxWidth: '350px' }}>{detailData?.foreignKey || '-'}</span>
                {detailData.foreignKey && <span onClick={() => copyEvent(detailData?.foreignKey)} className='ml-1 image-content'><Image alt='DB-GPT' height={15} width={15} src='/ai/workbenches/tabler-icon-copy.png' /></span>}
              </li>
            </div>
          </ul>
          <ul className='inDetail-content-ul'>
            <h3 className='title'>列</h3>
            <Table
              className='scrollbarStyle'
              columns={dataTableColumn}
              dataSource={dataSource}
              pagination={false}
              scroll={{ y: '450px' }}
            />
          </ul>
          <ul className='inDetail-content-ul'>
            <h3 className='title'>模型</h3>
            <li style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', maxHeight: '200px', overflowY: 'auto' }}  >{detailData.modelDetail && detailData.modelDetail.map((item, index) => (<div className='model-list' key={index}><span>{item}</span><span onClick={() => copyEvent(item)} className='ml-2 model-list-copy image-content cursor-pointer'><Image alt='DB-GPT' height={13} width={15} src='/ai/workbenches/tabler-icon-copy.png' /></span></div>))}</li>
          </ul>
        </div>
        </div>
      </div>) : <Drawer
        bodyStyle={{ padding: 0 }}
        title=""
        placement='bottom'
        closable={false}
        onClose={() => onClose(false)}
        height={'400px'}
        width={'100%'}
        open={open}
        mask={false}
        getContainer={false}
      >
        <div className='inDetail-content'>
          {activeKey != 'table' && (<div className='flex items-center justify-between' style={{ padding: '0 10px 0 0' }}>
            <Tabs
              hideAdd
              onChange={onChange}
              activeKey={activeKey}
              type="editable-card"
              onEdit={onEdit}
              items={tabList}
            />
            <div>
              <DownOutlined className='ml-2' onClick={() => onClose(false)} />
            </div>
          </div>)}
          <div style={style}>
            {activeKey === 'model' && (<div>
              <ul className='inDetail-content-ul'>
                <h3 className='title'>基本信息</h3>
                <li><span>名称：</span><span>{basicData?.name}</span></li>
                <li><span>注释：</span>{(basicData?.comment && <span>{basicData?.comment}</span>)}</li>
                <li><span>领域：</span><div className='flex'>{basicData?.businessDomainNames && basicData.businessDomainNames.split(',').map((item, index) => (<p key={index}>{item}</p>))}</div></li>
                <li><span>创建者：</span>{basicData?.creatorName && (<span>{basicData?.creatorName}</span>)}</li>
                <li><span>创建时间：</span><span>{basicData?.createTime}</span></li>
                <li><span>发布时间：</span>{basicData?.publishTime && (<span>{basicData?.publishTime}</span>)}</li>
              </ul>
              <ul className='inDetail-content-ul'>
                <h3 className='title'>属性</h3>
                <Table
                  className='scrollbarStyle'
                  columns={columns}
                  dataSource={attributeList}
                  pagination={false}
                  scroll={{ y: '200px' }}
                />
              </ul>
              {activeKey === 'model' && (<ul className='inDetail-content-ul' >
                <h3 className='title'>数据&查询</h3>
                <li style={{ display: 'flex', flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'flex-start' }}>{basicData?.metricModelTables && basicData.metricModelTables.map(item => (<div className='flex items-center' style={{ marginBottom: '10px' }}><span>{item.tableType ? '查询' : '数据'}：</span><span>{item.comment}</span><span onClick={() => copyEvent(item.comment)} className='ml-1 image-content'><Image alt='DB-GPT' height={15} width={15} src='/ai/workbenches/tabler-icon-copy.png' /></span></div>))}</li>
              </ul>)}
              <ul className='inDetail-content-ul'>
                <h3 className='title'>模型加速</h3>
                <li><span>是否开启：</span><span>{basicData?.isAccelerationEnabled ? '是' : '否'}</span></li>
                <li><span>运行时间：</span><span>{basicData?.scheduleType === '1' ? '每月一次' : '每日一次'}{basicData?.executionTime}</span></li>
              </ul>
            </div>)}
            {activeKey === 'log' && (<div>
              <div className='search-content'>
                <div>
                  <Select
                    defaultValue="7"
                    style={{ width: 120 }}
                    onChange={handleChange}
                    options={[
                      { value: '7', label: '近七天' },
                      { value: '14', label: '近十四天' },
                      { value: '30', label: '近三十天' },
                    ]}
                  />
                  <ReloadOutlined style={{ fontSize: '16px', marginLeft: '10px', cursor: 'pointer' }} onClick={getindicatorModelLog} />
                </div>
                <Radio.Group defaultValue="a" buttonStyle="solid" onChange={handleRadioChange}>
                  <Radio.Button value="all">所有 <span>{logTableData.length}</span></Radio.Button>
                  <Radio.Button value="SUCCESS">成功 <span>{logTableData ? logTableData.filter(item => item.STATE === 'SUCCESS').length : 0}</span></Radio.Button>
                  <Radio.Button value="FAIL">失败 <span>{logTableData ? logTableData.filter(item => item.STATE != 'SUCCESS').length : 0}</span></Radio.Button>
                </Radio.Group>
              </div>
              <div>
                <Table
                  className='scrollbarStyle'
                  columns={logColumns}
                  dataSource={logDisplayData}
                  scroll={{ x: 'max-content', y: '300px' }}
                  pagination={false}
                  locale={{
                    emptyText: <Empty
                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                      description={
                        <Typography.Text>
                          暂无日志
                        </Typography.Text>
                      } >{logStatus == 'all' && (<Button color="default" variant="filled" onClick={getindicatorModelLog} icon={<ReloadOutlined />} >刷新</Button>)}</Empty>
                  }}
                />
              </div>
            </div>)}
            {activeKey === 'preview' && (<div>
              <div>
                <Table
                  className='scrollbarStyle scrollbarStyleover'
                  columns={previewColumns}
                  dataSource={previewDataSource}
                  scroll={{ x: 'max-content' }}
                  pagination={{
                    position: ['topLeft'],
                    total: previewDataCount,
                    pageSizeOptions: ['10', '20', '50', '100'], // 可选的每页条数
                    showSizeChanger: true,
                    showTotal: (total) => (<span style={{ display: 'inline-flex', alignItems: 'center' }}>
                      总数：{total}
                      <ReloadOutlined style={{ marginLeft: 8, cursor: 'pointer', fontSize: '16px' }}
                        onClick={getsqlExecutetotal}
                      />
                    </span>),
                    onChange: handlePageChange,
                    onShowSizeChange: handlePageSizeChange
                  }}
                />
              </div>
            </div>)}
          </div>
        </div>
      </Drawer>}
    </>
  );
};

export default inDetailContent;